package com.cbh.amadeus.server.handler;

import com.cbh.amadeus.server.domain.ChannelModel;
import com.cbh.amadeus.server.utils.TopicChannelManage;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;

/**
 * @author ChenBiHui
 * @date 2025/4/30
 */
@Slf4j
public class InactiveHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        ChannelModel channelModel = TopicChannelManage.findModelWithChannel(channel);
        if (channelModel == null) {
            log.info(
                    "===== [INACTIVE] Channel [{}] has leave register =====",
                    channel.remoteAddress()
            );
            super.channelInactive(ctx);
            return;
        }
        TopicChannelManage.remove(channel);
        log.info(
                "===== [INACTIVE] Channel [{} - {}] has leave register topic is [{}] =====",
                channel.remoteAddress(),
                channelModel.getName(),
                channelModel.getTopics()
        );
        super.channelInactive(ctx);
    }
}
